package com.rjhch.tonglink.client.jms.pub_sub;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
import javax.naming.Context;
import javax.naming.InitialContext;

public class TopicPubSubNewJNDI {
	public static final String tcf = "tongtech.jms.jndi.JmsContextFactory";

	public static final String remoteURL = "tlq://127.0.0.1:10025";
	public static final String remoteFactory = "RemoteTopicConnectionFactory";

	public static void main(String args[]) {
		
		TopicConnectionFactory topicCF = null;
		TopicConnection conn = null;
		TopicSession session = null;
		Topic topic = null;

		try {
			java.util.Properties prop = new java.util.Properties();
	
			prop.put("java.naming.factory.initial", tcf);
			prop.put("java.naming.provider.url", remoteURL);
			Context ctx = new InitialContext(prop);

			topicCF = (TopicConnectionFactory) ctx.lookup(remoteFactory);
			topic = (Topic) ctx.lookup("MyTopic");
			conn = topicCF.createTopicConnection();
			conn.start();

			session = conn.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
			TopicPublisher publisher = session.createPublisher(topic);
			TopicSubscriber subscriber = session.createSubscriber(topic);
			// TopicSubscriber subscriber =
			// session.createDurableSubscriber(topic, "durable");

			TextMessage message = session.createTextMessage();
			message.setText("TopicPubSubJNDI Message");
			System.out.println("发送消息...");
			publisher.publish(message);
			System.out.println("发送完成...");

			Message msg = subscriber.receive(1000);
			if (msg != null) {
				if (msg instanceof TextMessage) {
					TextMessage textMsg = (TextMessage) msg;
					System.out.println("subscriber收到Text消息:" + textMsg.getText());
				} else {
					System.out.println("subscriber收到非Text消息.");
				}
			} else {
				System.out.println("没有收到消息.");
			}

		} catch (Exception jmse) {
			System.out.println("Exception oxxurred :" + jmse.toString());
			jmse.printStackTrace();
		} finally {
			try {
				if (session != null) {
					session.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (Exception e) {
				System.out.println("退出时发生错误。");
				e.printStackTrace();
			}
		}
	}

	
}
